# -*- coding:utf-8 -*-

import json
import sqlite3
from datetime import datetime

class Config(object):
    def __init__(self):
        self.config = json.load(file("config.json"))

    def getconfig(self, configname):
        return self.config.get(configname, None)

class DbSession(object):
    def __init__(self, autocommit = True):
        dbfilename = Config().getconfig("dbfilename")
        self.conn = sqlite3.connect(dbfilename)
        self.cursor = None

    def selectall(self, sql, params = None):
        if params:
            sqltpl = sql % params
            return self.cursor.execute(sqltpl).fetchall()
        else:
            return self.cursor.execute(sql).fetchall()

    def selectone(self, sql, params = None):
        if params:
            sqltpl = sql % params
            print(sqltpl)
            return self.cursor.execute(sqltpl).fetchone()
        else:
            return self.cursor.execute(sql).fetchone()

    def update(self, sql, params = None):
        if params:
            sqltpl = sql % params
            return self.cursor.execute(sqltpl)
        else:
            return self.cursor.execute(sql)

    def getCount(self,sql,params = None):
        try:
            with DbSession as session:
                total=session.selectone(sql)
                return total[0]
        except:
            return 0
            
    def __enter__(self):
        self.cursor = self.conn.cursor()
        return self

    def __exit__(self, x, y ,z):
        try:
            self.conn.commit()
            self.cursor.close()
            self.conn.close()
        except:
            pass

def getcurrdatestr():
    now = datetime.now()
    datestr = "%d-%02d-%02d %02d:%02d:%02d" % (
            now.year, now.month, now.day,
            now.hour, now.minute, now.second
            )
    return datestr

if __name__ == '__main__':
    pass
